var http = require('http')
  , exec = require('exec')
  , execSync = require("child_process").execSync

const PORT = 8002
  , BASE_PATH = '~/docker/'

var deployServer = http.createServer(function(request, response) {
  if (request.url.search(/deploy\/.*/i) > 0) {
    var object_name="um_server"
    var object_url = request.url.split("/")[2]
    var dockerIDCMD="docker ps -aqf name="+object_url
    var docker_id = execSync(dockerIDCMD)
    if(object_url == "docker-um-timer-server"){
      object_name="um_timer_server"
    }
    var commands = [
      'cd ' + BASE_PATH + object_url,
      'git pull origin master',
      'sudo rm -rf /var/src/' + object_url + '/*',
      'sudo cp -rf scripts/'+ object_name +'/* /var/src/' + object_name + '/',
      'docker restart ' + docker_id
    ].join(' && ')

    exec(commands, function(err, out, code) {
      if (err instanceof Error) {
        response.writeHead(500)
        response.end('Server Internal Error.')
        throw err
      }

      process.stderr.write(err)
      process.stdout.write(out)
      response.writeHead(200)
      response.end('Deploy Done.')

    })

  } else {

    response.writeHead(404)
    response.end('Not Found.')

  }
})

deployServer.listen(PORT)